<template>
  <div class="login">
    <form class="login-container">
      <div class="list">
        <div class="phone">
          <img
            class="phone_img"
            width="22"
            height="22"
            src="https://gw.alicdn.com/tfs/TB1P_lmOhTpK1RjSZFKXXa2wXXa-36-34.png"
            alt
          >
          <img
            class="jia_img"
            src="https://gw.alicdn.com/tfs/TB1JZJpOgHqK1RjSZFPXXcwapXa-26-26.png"
            alt
          >
          <p>86</p>
          <p class="line"></p>
          <input
            @blur="out"
            type="tel"
            maxlength="11"
            v-model="inform.phone"
            placeholder="请输入手机号码"
            onKeyPress="if((event.keyCode<48 || event.keyCode>57) && event.keyCode!=46 || /\.\$/.test(value))event.returnValue=false"
            >
        </div>
        <div class="code-box">
          <div class="phone code-content">
            <img
              class="phone_img"
              width="22"
              height="22"
              src="https://gw.alicdn.com/tfs/TB19KVnOkvoK1RjSZPfXXXPKFXa-34-34.png"
              alt
            >
            <input @blur="out" type="number" maxlength="6" v-model="inform.phonecode" placeholder="验证码">
          </div>
          <button class="btn" :disabled="isdis" @click.prevent="getcode">{{inpval}}</button>
        </div>
        <div class="btnFrom" v-if="!inform.phonecode" :class="inform.phonecode?'conten2':'conten1'">
          <div>登录</div>
        </div>
        <div class="btnFrom" v-else :class="inform.phonecode?'conten2':'conten1'" @click="delpass">
          <div>登录</div>
        </div>
      </div>
    </form>
  </div>
</template>
<script>
import { getLoginCode } from "@/api/login";
import { setToken, getToken, removeToken } from "@/utils/auth";
import { clearTimeout } from "timers";
import other from "@/utils/other";
 import { Debounce, Throttle } from "@/utils";

export default {
  name: "login",
  data() {
    return {
       code: "",
      appid: "",
      Secret: "",
      portrait: "",
      state: "", //state=workweixin是企业微信。state=weixin是服务号登录
      inpval: "获取验证码",
      inform: {},
      status: "", //获取公司状态，1是多公司
      isdis: false,
      isShow: false,
      isStatus: false, //获取公司状态，1是多公司
      countdown: 60,
      resurecode: "",
      show: false, // 弹框的显示
      overlay: true, // 蒙版层的显示
      columns: [], // 公司列表数据
      companyName: "", // 公司名称,
      losCompany: [] //通过登录接口获取公司
    };
  },
  methods: {
    out() {
      other.inputBlur();
    },
   delpass:Throttle(function () {
      if (!this.inform.phone) {
        this.$toast("请输入手机号");
        return;
      }
      if (!this.inform.phonecode) {
        this.$toast("请输入验证码");
        return;
      }
      this.WxLogin();
    },1000),
    getcode() {
      if (!this.inform.phone) {
        this.$toast("请输入手机号");
        return;
      }
      if (this.inform.phone.length != 11) {
        this.$toast("请输入正确的手机号");
        return;
      }
      this.fun();
      this.codeLogin();
    },
    async codeLogin() {
      let pra = {
        phone: this.inform.phone
      };
      let query = Object.assign({}, pra);
      let { data } = await getLoginCode(query);
      if (data.status == 100) {
        this.$toast("验证码获取成功");
      } else {
        this.$toast("验证码获取失败");
      }
    },
    fun() {
      if (this.countdown == 0) {
        this.isdis = false;
        this.inpval = "免费获取验证码";
        this.countdown = 60;
        return;
      } else {
        this.isdis = true;
        this.inpval = "重新发送(" + this.countdown + ")";
        this.countdown--;
      }
      let this_ = this;
      setTimeout(function() {
        this_.fun();
      }, 1000);
    },
    //点击登录
    WxLogin() {
        let pamart = {
            phone: this.inform.phone,
            code: this.inform.phonecode,
            company_id: this.inform.company_id || localStorage.getItem("companyId"),
            portrait: localStorage.getItem("headimgurl"),
            sysStatus: localStorage.getItem("sysStatus")
        };
        if (localStorage.getItem("sysStatus") == 1) {
          pamart.user_id = localStorage.getItem("openid")
        } else if (localStorage.getItem("sysStatus") == 2) {
          pamart.user_id = localStorage.getItem("userId")
        } else if (localStorage.getItem("sysStatus") == 3) {
          
        }
        let query = Object.assign({}, pamart);
        this.$store.dispatch('weXinLogin', query).then(res => {
          localStorage.setItem("oss_public_url", 'https://saic-public-2.oss-cn-shanghai.aliyuncs.com');
          localStorage.setItem("user", JSON.stringify(res.user));
          localStorage.setItem("companyId", res.user.company_id);
          localStorage.setItem("headimgurl", res.portrait);
          setToken({ key: res.token_key, val: res.token });
          localStorage.setItem('token',res.token)
          this.$toast("登录成功");
          this.$router.replace('/Container')
        }).catch(error =>{
          if (error.data.status == 101) {
            if (error.data.msg == '缺少user_id参数') {
              this.$toast(error.data.msg + '请退出到入口重新进入');
            }else{
              this.$toast(error.data.msg || "登录失败");
            }
          }
        })
    },
    //钉钉免登
    authSerivce: function() {
      let that = this;
      dd.ready(function() {
        dd.runtime.permission.requestAuthCode({
          corpId: localStorage.getItem("corpId"), //hmw
          onSuccess: function(result) {
            localStorage.setItem("code", result.code);
            that.wxUserData();
          },
          onFail: function(err) {
            if (err.status == 101) {
              Dialog.alert({
                message: "请联系管理员添加权限"
              }).then(() => {
                // on close
              });
            }
          }
        });
      });
    },
    // 获取用户信息
    wxUserData(){
      let app = localStorage.getItem("appid");
      let app1 = app.split("-");
      let appid = app1[0];
      let Secret = app1[1];
      let params = {}
      if (localStorage.getItem("sysStatus") == 1) {
        params = {
          code: localStorage.getItem("code"),
          appkey: appid,
          appsecret: Secret,
          company_id: localStorage.getItem("companyId"),
          sysStatus: localStorage.getItem("sysStatus")
        }
      } else if (localStorage.getItem("sysStatus") == 2) {
        params = {
          code: localStorage.getItem("code"),
          appkey: localStorage.getItem("appKey"),
          appsecret: localStorage.getItem("appSecret"),
          company_id: localStorage.getItem("companyId"),
          sysStatus: localStorage.getItem("sysStatus")
        }
        
      } else if (localStorage.getItem("sysStatus") == 3) {
        
      }
      let query = Object.assign({}, params);
      this.$store.dispatch('wxUserDataList', query).then(res => {
          if (res.token) {
            this.portrait = res.headimgurl;
            if (localStorage.getItem("sysStatus") == 1) {
              localStorage.setItem("headimgurl", res.headimgurl);
            }else if (localStorage.getItem("sysStatus") == 2) {
              localStorage.setItem("headimgurl", res.portrait);
            }
            localStorage.setItem("user", JSON.stringify(res.user));
            this.openid = res.openid;
            localStorage.setItem("openid", res.openid);
            localStorage.setItem("userId", res.userid);
            localStorage.setItem('token',res.token)
            setToken({ key: res.user.token_key, val: res.token });
            this.$router.replace('/Container')
          } 
          if (res.token == null || res.token == ''){
            localStorage.setItem("openid", res.openid);
            localStorage.setItem("headimgurl", res.headimgurl);
            localStorage.setItem("userId", res.userid);
            if (localStorage.getItem("sysStatus") == 1) {
              localStorage.setItem("headimgurl", res.headimgurl);
            }else if (localStorage.getItem("sysStatus") == 2) {
              localStorage.setItem("headimgurl", res.portrait);
            }
            this.portrait = res.headimgurl;
            localStorage.setItem("user", JSON.stringify(res));
            localStorage.setItem('token',res.token)
            this.openid = res.openid;
            removeToken();
             window.localStorage.removeItem("token");
            // window.localStorage.clear()
            
            this.$router.replace('/Login')
          }
      }).catch( error => {

      })
    }
  },
  created() {
    if (this.$route.query.name == 'layout') {
      localStorage.setItem("companyId",localStorage.getItem('state')? localStorage.getItem('state').substr(localStorage.getItem('state').length-3,1) : null); 
      localStorage.setItem("sysStatus", localStorage.getItem('state')? localStorage.getItem('state').substr(localStorage.getItem('state').length-1,1) : null);   // 1 微信  2 钉钉  3 企业微信
      if (localStorage.getItem("sysStatus") == 3) {
        this.EwxUserId();
      } else if (localStorage.getItem("sysStatus") == 1) {
        this.wxUserData();
      } else if (localStorage.getItem("sysStatus") == 2) {
        this.authSerivce();
      }
    }
    
  }
};
</script>
<style lang="scss" scoped>
@import "Login";
</style>

